<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-position="top">
    <!-- <el-form-item> -->
    <div class="flex-x-between mb-10" style="width: 100%">
      <div v-if="addTitle">{{ addTitle }}</div>
      <div>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </div>
    <!-- </el-form-item> -->
    <el-row :gutter="10">
      <el-col v-for="field in fields" :key="field.name" :span="field.span || 12">
        <el-form-item :label="field.label" :prop="field.name" :rules="field.validationRules">
          <component
            :is="getFieldComponent(field.type)"
            v-model="form[field.name]"
            :options="field.options"
            :type="field.type"
          ></component>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Fields } from "./formConfig";
// 注册各个字段类型的组件
import Input from "./components/Input.vue";
import Select from "./components/Select.vue";
import Radio from "./components/Radio.vue";
import DatePicker from "./components/DatePicker.vue";

interface Props {
  fields: Fields[];
  addTitle?: String;
}

const props = defineProps<Props>();
const form = ref<{ [key: string]: any }>({});
const rules = ref<{ [key: string]: any }>({});
const formRef = ref();

const getFieldComponent = (type: string) => {
  if (["input", "text", "textarea", "password", "number"].includes(type)) {
    return Input;
  }
  if (type == "select") {
    return Select;
  }
  if (type == "radio") {
    return Radio;
  }
  if (["year", "month", "date", "dates", "datetime", "week", "datetimerange", "daterange", "monthrange"].includes(type)) {
    return DatePicker;
  }
  // if (type == "upload") {
  //   return Radio;
  // }
  return null;
};

const emit = defineEmits(["save"]);
const handleSubmit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      emit("save", form.value);
      formRef.value.resetFields();
    }
  });
};

const handleReset = () => {
  formRef.value.resetFields();
};

props.fields.forEach(field => {
  rules.value[field.name] = field.validationRules;
});
</script>

<style>
.el-row {
  margin-bottom: 15px;
}
</style>
